# -*- coding: UTF-8 -*-
"""
@File    :   choose_db.py
@Date    :   2022/05/26
@Author  :   Qiuye Lin 
@License :   # Copyright (C) 2022, Qiuye Lin. All Rights Reserved.
@Desc    :   数据库链接及查询
"""

import time

import pymysql
from commons.config_tools import Cf
from commons.logger import log


class ConnDB:
    def __init__(self, note: str):
        setting = {
            'host': Cf.read_config_ini(note, 'host'),
            'port': int(Cf.read_config_ini(note, 'port')),
            'user': Cf.read_config_ini(note, 'user'),
            'password': Cf.read_config_ini(note, 'password'),
            'database': Cf.read_config_ini(note, 'database')
        }
        log.debug(f"========Connect Database - {note}========")

        # 创建数据库连接
        self.conn = pymysql.connect(
            **setting,
            charset="utf8",
            cursorclass=pymysql.cursors.DictCursor,
        )

        # 创建游标对象
        self.cursor = self.conn.cursor()

    def __enter__(self):
        # 返回类实例化对象
        return self

    def __exit__(self, exc_type, exc_value, exc_trace):
        self.cursor.close()
        self.conn.close()
        time.sleep(0.5)

    def __del__(self):
        if self.conn.open:
            log.debug("Close the connection.")
            self.cursor.close()
            self.conn.close()

    def query(self, sql_str):
        log.debug("执行查询操作")
        try:
            self.cursor.execute(sql_str)
            log.debug(sql_str)
            result = self.cursor.fetchall()
            log.debug("查询完成")
            return result
        except pymysql.Error as e:
            self.conn.rollback()
            log.debug(e)
            raise e

    def exec(self, sql_str):
        try:
            log.debug("执行删除/更新操作")
            log.debug(sql_str)
            self.cursor.execute(sql_str)
            self.conn.commit()
            log.debug("删除/更新操作完成")
            return self.cursor.fetchall()
        except pymysql.Error as e:
            self.conn.rollback()
            log.debug(e)
            raise pymysql.Error
